﻿using System.Collections.Generic;
using System.Reflection.Emit;
using Microsoft.EntityFrameworkCore;
using PublisherManagementSystem.Models;

namespace PublisherManagementSystem.DAL
{
	public class PublisherDbContext : DbContext
	{
		public PublisherDbContext(DbContextOptions<PublisherDbContext> options)
		: base(options)
		{
		}

		// 定义数据库表对应的DbSet
		public DbSet<Province> Provinces { get; set; }
		public DbSet<City> Cities { get; set; }
		public DbSet<District> Districts { get; set; }
		public DbSet<Publisher> Publishers { get; set; }
		public DbSet<PublisherStaff> PublisherStaffs { get; set; }

		// 配置模型关系（Fluent API）
		protected override void OnModelCreating(ModelBuilder modelBuilder)
		{
			// 配置出版社与人员的一对多关系
			modelBuilder.Entity<Publisher>()
				.HasMany(p => p.Staffs)
				.WithOne(s => s.Publisher)
				.HasForeignKey(s => s.PublisherID)
				.OnDelete(DeleteBehavior.Restrict); // 使用Restrict避免级联删除

			// 配置省市县的层级关系
			modelBuilder.Entity<City>()
				.HasOne(c => c.Province)
				.WithMany(p => p.Cities)
				.HasForeignKey(c => c.ProvinceID)
				.OnDelete(DeleteBehavior.Restrict);

			modelBuilder.Entity<District>()
				.HasOne(d => d.City)
				.WithMany(c => c.Districts)
				.HasForeignKey(d => d.CityID)
				.OnDelete(DeleteBehavior.Restrict);

			// 为电话号码添加唯一索引
			modelBuilder.Entity<Publisher>()
				.HasIndex(p => p.Phone)
				.IsUnique();

			modelBuilder.Entity<PublisherStaff>()
				.HasIndex(s => s.Phone)
				.IsUnique();

			modelBuilder.Entity<PublisherStaff>()
				.HasIndex(s => s.Email)
				.IsUnique();

			// 全局配置：禁用所有关系的级联删除
			foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
			{
				relationship.DeleteBehavior = DeleteBehavior.Restrict;
			}
		}
	}
}
